package work.huangxin.share.controller.admin;

import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import work.huangxin.share.constant.RedisConstant;
import work.huangxin.share.domain.admin.UserBlock;
import work.huangxin.share.domain.admin.dto.UserCountDto;
import work.huangxin.share.domain.other.UserMessage;
import work.huangxin.share.mapper.UserMessageMapper;
import work.huangxin.share.service.AdminUserService;
import work.huangxin.share.util.RedisUtil;
import work.huangxin.share.util.status.BaseResponse;
import work.huangxin.share.util.status.CodeEnum;
import work.huangxin.share.util.status.ResponseData;


import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ThreadPoolExecutor;

/**
* @author 钟声浩
* @date 2023/4/4 18:39
*/
@RestController
@RequestMapping("/wx/admin/api/adminUser")
public class AdminUserController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private UserMessageMapper userMessageMapper;

    //分页查询所有用户
    @PostMapping("/getAllUser")
    public BaseResponse getAllUserList(@RequestBody UserMessage userMessage,
                                       @RequestParam Integer pageNum,
                                       @RequestParam Integer pageSize) {
        PageInfo<UserMessage> pageInfo = adminUserService.selectPageUserList(userMessage, pageNum, pageSize);
        if (Objects.isNull(pageInfo)) {
            return ResponseData.out(CodeEnum.NOT_FOUND, "数据丢失");
        }
        return ResponseData.success(pageInfo);
    }

    //根据userId查询用户详细信息
    @GetMapping("/getUserDetail/{userId}")
    public BaseResponse getUserDetail(@PathVariable Integer userId) {
        UserMessage userMessage = adminUserService.getUserDetailByUserId(userId);
        if (Objects.isNull(userMessage)) {
            return ResponseData.out(CodeEnum.NOT_FOUND, "数据错误");
        }
        return ResponseData.success(userMessage);
    }

    /**
     * 用户的拉黑和解除拉黑都由管理员操作。
     */
//    //拉黑指定用户
//    //每次发起请求时，相关的方法 CheckAllow 会判断 user_allow 是否为 2
//    @PostMapping("/blockUser/{userId}")
//    public BaseResponse blockUser(@PathVariable Integer userId) {
//        int i = userMessageMapper.updateUserNotAllowByUserId(userId);
//        if (i <= 0) {
//            return ResponseData.out(CodeEnum.FAIL, "拉黑用户失败!");
//        }
//        return ResponseData.success();
//    }
//
//    //解除对用户的拉黑
//    @PostMapping("/unlockUser/{userId}")
//    public BaseResponse unlockUser(@PathVariable Integer userId) {
//        int i = userMessageMapper.updateUserAllowByUserId(userId);
//        if (i <= 0) {
//            return ResponseData.out(CodeEnum.FAIL, "解除拉黑用户失败!");
//        }
//        return ResponseData.success();
//    }

    /**
     * 进阶版拉黑用户，自动设置拉黑时间，且自动解除拉黑
     */
    //拉黑用户
    @Transactional
    @PostMapping("/blockUser/{userId}")
    public BaseResponse blockUserByUserId(@PathVariable("userId") Integer userId,
                                          @RequestParam Integer blockDay) {
        //如果时间小于-1，则是无期限拉黑。因为时间是秒
        boolean hasValue = redisUtil.sHasKey(RedisConstant.USER_BLOCK_LIST + userId, "");
        if (hasValue) {
            return ResponseData.out(CodeEnum.FAIL, "该用户已经被拉黑");
        }
        long hasBeenBlock = redisUtil.sSetAndTime(RedisConstant.USER_BLOCK_LIST + userId, blockDay * 60 * 60 * 24, "");
        Long expireTime = System.currentTimeMillis() + blockDay * 60 * 60 * 24 * 1000;
        UserBlock userBlock = new UserBlock(userId, expireTime);
        threadPoolExecutor.execute(() -> {
            adminUserService.lockUserAndNotAllow(userBlock, userId);
        });
        return ResponseData.success();
    }

    //解除对用户的拉黑
    @Transactional
    @PostMapping("/unlockUser/{userId}")
    public BaseResponse unblockUserByUserId(@PathVariable("userId") Integer userId) {
        //先判断用户是否在拉黑名单中
        boolean has = redisUtil.sHasKey(RedisConstant.USER_BLOCK_LIST + userId, "");
        //如果存在在黑名单中，就删掉redis中缓存的数据
        if (!has) {
            return ResponseData.out(CodeEnum.FAIL, "该用户未被拉黑");
        }
        redisUtil.setRemove(RedisConstant.USER_BLOCK_LIST + userId, "");
        threadPoolExecutor.execute(() -> {
            adminUserService.unlockUserAndAllow(userId);
        });
        return ResponseData.success();
    }




    //编辑用户信息
    @PutMapping("/editUser")
    public BaseResponse edit(@RequestBody UserMessage userMessage) {
        int count = userMessageMapper.editUser(userMessage);
        if (count <= 0) {
            return ResponseData.out(CodeEnum.NOT_FOUND, "数据错误");
        }
        return ResponseData.success();
    }
    /**
     * 获得本月新增用户数
     */
    @GetMapping("/getNewUserCount")
    public BaseResponse getNewUserCount(){
        int newUserCount = adminUserService.getNewUserCount();
        return ResponseData.success(newUserCount);
    }

    /**
     * 新增用户的数量
     */
    @GetMapping("/userCountByYearAndMonth")
    public List<UserCountDto> getUserCountByYearAndMonth(@RequestParam(value = "year", required = false) Integer year,
                                                         @RequestParam(value = "month", required = false) Integer month) {
        return adminUserService.getUserCountByYearAndMonth(year, month);
    }

}
